﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Configuration;
using ueEngine.Framework.Common;
using System.Net;
using System.Web;
using System.Threading;

namespace DataPump
{
    public class ganjiResource : IResource
    {
        static Random random = new Random();
        public DateTime StartTime = DateTime.Now;
        const string Prefix = "http://cq.ganji.com";
        const string baseImgDir = "/content/resource/phoneImg/";
        public ganjiResource(string constr,DateTime startTime)
            : base(constr)
        {
            this.StartTime = startTime;

            if (!Directory.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + baseImgDir))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + baseImgDir);
            }
        }
        public Dictionary<int, string> Get
        {
            get
            {
                return dict;
            }
        }
        protected override void SetDict()
        {
            dict.Add(1, "/jzcuxiaoyuan/");//促销员
            //dict.Add(2, "/jzjianzhimote/");//模特
            //dict.Add(3, "/jzliyixiaojie/");//礼仪小姐
            dict.Add(4, "/jzjiajiaolaoshi/");//家教
            dict.Add(5, "/jzshougongzhizuo/");//手工制作
            dict.Add(6, "/jzfuwuyuan/");//服务员
            dict.Add(7, "/jzxuesheng/");//学生兼职
            dict.Add(8, "/jzchuandanpaifa/");//传单派发
            dict.Add(9, "/jzwangzhanjianshe/");//网站建设
            dict.Add(10, "/jzjianzhikuaiji/");//会计
            dict.Add(11, "/jzshixisheng/");//实习生
            dict.Add(12, "/jzxiaoshigong/");//小时工/钟点工
            dict.Add(13, "/jzjianzhifanyi/");//翻译
            dict.Add(14, "/jzwenjuandiaocha/");//问卷调查
            dict.Add(15, "/jzqunzhongyanyuan/");//群众演员
            dict.Add(16, "/jzxiaoshou/");//销售
            dict.Add(17, "/jzshejizhizuo/");//设计制作
            dict.Add(18, "/jzsheyingshi/");//摄影师
            dict.Add(19, "/qitajianzhi/");//其他兼职
            //dict.Add(20, "/jzjiuba/");//酒吧KTV
        }
        public override void Do()
        {
            //List<Info> all = new List<Info>();
            foreach (var item in Get)
            {
                try
                {
                    LogHelper.Write(CommonLogger.System, LogLevel.Info, "request:" + Prefix + item.Value);
                    //分类列表
                    string html = Common.DoRequest(Prefix + item.Value);
                    Analysts(html, item.Value, ref total);
                    Thread.Sleep(100);
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
                }
            }
        }
        protected override void Analysts(string html, string uri, ref int count)
        {
            string listbody = Pickbody(html);
            MatchCollection mc = new Regex("\\<dl\\s+class=\"list-noimg\\s+job-list\\s*\".*?\\>.*?\\<\\/dl\\>").Matches(listbody);
            foreach (Match match in mc) //遍历列表
            {
                Thread.Sleep(1000);
                count++;
                try
                {
                    Info info = new Info();
                    string s = match.Value;
                    //XElement xe = XElement.Parse(s.Replace("&nbsp;", ""));
                    string url = new Regex("(?<=name=\"send_resume\"/?>\\s*<a\\s*(class=\"list_title\"\\s*)?href=\").*?(?=\")").Match(s).Value;
                    //new Regex("(?<=name=\"send_resume\"/>\\s*<a href=\").*?(?=\")").Match(s).Value;
                    //string url = xe.Element("dt").Element("a").Attribute("href").Value;
                    /****设置对应的id****/
                    info.orgId = url;

                    //获得一条具体的一条信息页面
                    string detail = Common.DoRequest(ganjiResource.Prefix + url);
                    string pagebody = Pickbody(detail);

                    //兼职信息
                    info.Caption = new Regex("(?<=<h1\\s+class=\"f24\\s+fc4b\\s+h31\">).*?(?=</h1>)").Match(pagebody).Value.EmptyHTMLLabel();
                    if (String.IsNullOrEmpty(info.Caption.Trim()))
                    {
                        jumpwitherror++;
                        continue;
                    }
                    string pub_date = new Regex("(?<=<p\\s+class=\"fc70\\s+mb-5\">.*?)\\d{2}-\\d{2}\\s\\d{1,2}\\:\\d{1,2}(?=</span>)").Match(pagebody).Value;
                    DateTime ctTime = (DateTime.Now.Year.ToString() + "-" + pub_date).ToDate();
                    if (ctTime < StartTime)
                    {
                        jumpwithtime++;
                        continue;
                    }
                    info.ContactMan = new Regex("(?<=<dd>联\\s*系\\s*人：).*?(?=\\s)").Match(pagebody).Value.NoHTMLLabel();
                    if (!pagebody.Contains("联系电话："))
                    {
                        continue;
                    }
                    Match contactPhoneMatch = new Regex("(?<=<dd.*?>联系电话：.*?).*?(?=</dd>)").Match(pagebody);
                    if (!String.IsNullOrEmpty(contactPhoneMatch.Value))
                    {
                        if (contactPhoneMatch.Value.Contains("isShowPhone"))
                        {
                            var showImg = new Regex("(?<=<span.*?id=\"isShowPhoneTop\".*?>).*?(?=</span>)").Match(contactPhoneMatch.Value);
                            if (!String.IsNullOrEmpty(showImg.Value))
                            {
                                info.ContactPhone = showImg.Value;
                            }
                        }
                        else
                        {
                            info.ContactPhone = contactPhoneMatch.Value;
                        }
                        //info.ContactPhone = contactPhoneMatch.Groups[1].Value;
                        if (info.ContactPhone.Trim().Contains("<img"))
                        {
                            string phomeimg = new Regex("(?<=src=\").*?(?=\")").Match(info.ContactPhone).Value;
                            if (String.IsNullOrEmpty(phomeimg))
                            {
                                info.ContactPhone = "";
                            }
                            using (WebClient wc = new WebClient())
                            {
                                int squence = random.Next(100, 999);
                                string virpath = baseImgDir + DateTime.Now.ToString("yyyyMMddHHmmssfff") + squence.ToString() + ".png";
                                wc.Headers.Add("User-Agent", "Chrome");
                                wc.DownloadFile(Prefix + phomeimg, AppDomain.CurrentDomain.SetupInformation.ApplicationBase +
                                    virpath);
                                info.ContactPhone = virpath;
                            }
                        }
                        else
                        {
                            info.ContactPhone = info.ContactPhone.NoHTMLLabel();
                        }
                    }
                    //info.ContactPhone = new Regex("(?<=<dd.*?>联系电话：.*?).*?(<img.*?>).*?(?=</dd>)").Match(pagebody).Value;
                    
                    if (String.IsNullOrEmpty(info.ContactPhone))
                    {
                        jumpwithempty++;
                        continue;
                    }
                    info.Address = new Regex("(?<=工作地点：).*?(?=</em>)").Match(pagebody).Value.NoHTMLLabel();
                    //info.Area = MappingWorkArea(info.Address);

                    //职位
                    info.PositionType = PositionTypeMapping(uri);
                    info.PositionName = PositionNameMapping(uri);
                    info.Vacancy = new Regex("(?<=招聘人数：.*?<em>).*?(?=</em>)").Match(pagebody).Value.NoHTMLLabel();
                    info.Salry = new Regex("(?<=薪资待遇：.*?<em>).*?(?=</em>)").Match(pagebody).Value.NoHTMLLabel();
                    info.Degree = new Regex("(?<=最低学历：.*?<em>).*?(?=</em>)").Match(pagebody).Value.NoHTMLLabel();
                    info.Experience = new Regex("(?<=工作经验：.*?<em>).*?(?=</em>)").Match(pagebody).Value.NoHTMLLabel();
                    //info.PositionDescript = new Regex("(?<=<h3>职位描述</h3>\\s*<div class=\"summary-box\">).*?(?=</div>)").Match(pagebody).Value;
                    //info.PositionDescript = new Regex("</?a.*?>").Replace(info.PositionDescript, "");
                    info.PositionDescript = new Regex("(?<=class=\"deta-Corp\">).*?(?=</div>)").Match(pagebody).Value;
                    //info.PositionDescript = new Regex("(?<=class=\"summary-box\"\\s*style=\"margin-top:20px;\">).*?(?=</div>)").Match(info.PositionDescript).Value;
                    info.PositionDescript = info.PositionDescript.NoHTMLLabel("a").Trim();
                    foreach (var fb in Forbiddens)
                    {
                        if (!String.IsNullOrEmpty(fb) &&
                            info.PositionDescript.IndexOf(fb) > 0)
                        {
                            jumpwithganji++;
                            continue;
                        }
                    }
                    //公司信息
                    //info.CompanyName = xe.Element("dd").Element("a").Attribute("title").Value;
                    info.CompanyName = new Regex("(?<=target=\"_blank\"\\s*title=\").*?(?=\")").Match(s).Value.NoHTMLLabel();
                    info.CopBusiness = new Regex("(?<=公司行业：).*?(?=</span>)").Match(pagebody).Value.NoHTMLLabel();
                    info.CopType = new Regex("(?<=公司性质：).*?(?=</span>)").Match(pagebody).Value.NoHTMLLabel();
                    info.CopDimensions = new Regex("(?<=公司规模：).*?(?=</span>)").Match(pagebody).Value.NoHTMLLabel();
                    //info.CopAbout = new Regex("(?<=<h3>公司介绍:</h3>\\s*?<div class=\"summary-box\">).*?(?=</div>)").Match(pagebody).Value;
                    info.CopAbout = new Regex("(?<=公司介绍</h4>).*?(?=</p>)").Match(pagebody).Value.NoHTMLLabel();
                    //info.CopAbout = new Regex("(?<=class=\"summary-box\"\\s*style=\"margin-top:20px;\">).*?(?=</div>)").Match(info.CopAbout).Value.NoHTMLLabel("a").Trim();
                    //data.Add(info);
                    //Console.Write("解析完第：" + count + "条数据");
                    //****
                    if (PostData(info) == 1)
                    {
                        recrod++;
                    }
                    else
                    {
                        repeat++;
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.WebError, LogLevel.Error, e);
                    jumpwitherror++;
                    //Console.WriteLine("第：" + count + "条数据解析异常");
                }
            }
            //return data;
        }
        protected override int PositionTypeMapping(string uri)
        {
            switch (uri)
            {
                case "/jzcuxiaoyuan/"://促销员
                    return 1;
                case "/jzjianzhimote/"://模特
                    return 2;
                case "/jzliyixiaojie/"://礼仪小姐
                    return 3;
                case "/jzjiajiaolaoshi/"://家教
                    return 4;
                case "/jzshougongzhizuo/"://手工制作
                    return 5;
                case "/jzfuwuyuan/"://服务员
                    return 6;
                case "/jzxuesheng/"://学生兼职
                    return 7;
                case "/jzchuandanpaifa/"://传单派发
                    return 8;
                case "/jzwangzhanjianshe/"://网站建设
                    return 9;
                case "/jzjianzhikuaiji/"://会计
                    return 10;
                case "/jzshixisheng/"://实习生
                    return 11;
                case "/jzxiaoshigong/"://小时工/钟点工
                    return 12;
                case "/jzjianzhifanyi/"://翻译
                    return 13;
                case "/jzwenjuandiaocha/"://问卷调查
                    return 14;
                case "/jzqunzhongyanyuan/"://群众演员
                    return 15;
                case "/jzxiaoshou/"://销售
                    return 16;
                case "/jzshejizhizuo/"://设计制作
                    return 17;
                case "/jzsheyingshi/"://摄影师
                    return 18;
                default:
                case "/qitajianzhi/"://其他兼职
                    return 19;
                case "/jzjiuba/"://酒吧KTV
                    return 19;
            }

        }
        protected override string PositionNameMapping(string uri)
        {
            switch (uri)
            {
                case "/jzcuxiaoyuan/"://促销员
                    return "促销员";
                case "/jzjianzhimote/"://模特
                    return "模特";
                case "/jzliyixiaojie/"://礼仪小姐
                    return "礼仪小姐";
                case "/jzjiajiaolaoshi/"://家教
                    return "家教";
                case "/jzshougongzhizuo/"://手工制作
                    return "手工制作员";
                case "/jzfuwuyuan/"://服务员
                    return "服务员";
                case "/jzxuesheng/"://学生兼职
                    return "学生兼职";
                case "/jzchuandanpaifa/"://传单派发
                    return "传单派发员";
                case "/jzwangzhanjianshe/"://网站建设
                    return "网站建设/网站推广员";
                case "/jzjianzhikuaiji/"://会计
                    return "会计";
                case "/jzshixisheng/"://实习生
                    return "实习生";
                case "/jzxiaoshigong/"://小时工/钟点工
                    return "小时工";
                case "/jzjianzhifanyi/"://翻译
                    return "翻译";
                case "/jzwenjuandiaocha/"://问卷调查
                    return "问卷调查员";
                case "/jzqunzhongyanyuan/"://群众演员
                    return "群众演员";
                case "/jzxiaoshou/"://销售
                    return "销售员";
                case "/jzshejizhizuo/"://设计制作
                    return "设计制作者";
                case "/jzsheyingshi/"://摄影师
                    return "摄影师";
                default:
                case "/jzjiuba/":
                case "/qitajianzhi/"://其他兼职
                    return "兼职";
            }
        }
        public override int WorkAreaMapping(string str)
        {
            List<string> area = new List<string>{"渝中","沙坪坝","大学城","江北","渝北","九龙坡","北碚","大渡口",
                              "南岸","巴南","两江新区","周边" };
            var o = area.Select(c =>
            {
                return new { name = c, except = c.Intersect(str).Count() };
            })
            .OrderByDescending(c => c.except)
            .FirstOrDefault();
            if (o.except == 0)
            {
                return 12; //重庆周边
            }
            else
            {
                switch (o.name)
                {
                    case "渝中":
                        return 1;
                    case "沙坪坝":
                        return 2;
                    case "大学城":
                        return 3;
                    case "江北":
                        return 4;
                    case "渝北":
                        return 5;
                    case "九龙坡":
                        return 6;
                    case "北碚":
                        return 7;
                    case "大渡口":
                        return 8;
                    case "南岸":
                        return 9;
                    case "巴南":
                        return 10;
                    case "两江新区":
                        return 11;
                    case "周边":
                    default:
                        return 12;
                }
            }
        }
        protected override int CompanyBusinessMapping(string orgstr)
        {
            switch (orgstr.Trim())
            {
                case "教育/培训":
                    return 22;
                case "快速消费品(食品/饮料/烟酒/化妆品)":
                    return 5;
                case "运动健身":
                    return 23;
                case "广告/会展":
                    return 3;
                case "咨询/管理产业/法律/财会":
                    return 33;
                case "美容美发":
                    return 15;
                case "金融/银行/投资/基金/证券":
                    return 25;
                case "计算机/网络/通信":
                    return 9;
                case "建筑/装修":
                    return 26;
                case "超市/百货/零售":
                    return 5;
                case "环保":
                    return 20;
                case "耐用消费品(服装服饰/纺织/皮革/家具/家电)":
                    return 37;
                case "生产/制造":
                    return 2;
                case "酒店/餐饮":
                    return 1;
                case "媒体/影视/文化":
                    return 24;
                case "中介服务":
                    return 18;
                case "旅游":
                    return 27;
                case "石油/石化/化工":
                    return 12;
                case "跨领域经营":
                    return 38;
                case "贸易/交通/运输/物流":
                    return 6;
                case "农/林/牧/渔":
                    return 16;
                case "礼品/玩具/工艺美术/收藏品":
                    return 36;
                case "印刷/包装/造纸":
                    return 11;
                case "办公用品及设备":
                    return 5;
                case "物业管理/商业中心":
                    return 30;
                case "医药/生物工程":
                    return 35;
                case "保健按摩":
                    return 19;
                case "家政":
                    return 34;
                case "医疗设备/器械":
                    return 31;
                default:
                case "其它行业":
                    return 39;
            }
        }
        protected override int CompanyTypeMapping(string orgstr)
        {
            switch (orgstr.Trim())
            {
                case "民营":
                    return 2;
                case "上市公司":
                case "合资":
                case "股份制企业":
                    return 1;
                case "外商独资":
                    return 4;
                case "事业单位":
                case "国企":
                    return 3;
                default:
                case "其他":
                    return 5;
            }
        }
        protected override int CompanydimensionsMapping(string orgstr)
        {
            switch (orgstr.Trim())
            {
                case "20人以下":
                    return 1;
                case "20-99人":
                    return 2;
                case "100-499人":
                    return 3;
                default:
                case "500-999人":
                case "1000-9999人":
                case "10000人以上":
                    return 4;
            }
        }
        protected override int GenderMapping(string gender)
        {
            return -1; //不限
        }
        protected override int DegreeMapping(string degree)
        {
            switch (degree.Trim())
            {
                default:
                case "":
                case "不限":
                    return 0;
                case "高中/中专以上":
                case "大专":
                case "大专及以上":
                case "初中":
                case "初中以上":
                    return 1;
                case "本科":
                case "本科及以上":
                    return 2;
            }
        }
        protected override int ExperiencedMapping(string experience)
        {
            if (experience == "不限" || String.IsNullOrEmpty(experience))
            {
                return 0;
            }
            return 1;
        }
        protected override int VacancyMapping(string vacancy)
        {
            string s = new Regex("\\d+").Match(vacancy).Value;
            if (String.IsNullOrEmpty(s))
            {
                return 0;
            }
            int res = 0;
            if (Int32.TryParse(s, out res))
            {
                return res;
            }
            return 0;
        }
    }
}
